package cn.nexttec.noteplayer.common

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.constraintlayout.widget.ConstraintLayout
import cn.nexttec.lib_rich_editor.NoteListener
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.databinding.LayoutNotePanelHorizontalBinding
import kotlinx.coroutines.flow.combine

class FloatingToolbar(
    private val activity: Activity,
    private val launcher: ActivityResultLauncher<String>,
    private val rootView: ConstraintLayout
) : NoteListener {
    private var blinkAnimator: ObjectAnimator? = null
    private var isNoteEmpty: Boolean = true
    private lateinit var binding: LayoutNotePanelHorizontalBinding
    private var dX = 0f
    private var dY = 0f
    var isShowing: Boolean = false

    private var isResizing = false
    private var resizeStartTime = 0L
    private var initialTouchX = 0f
    private var initialTouchY = 0f
    private var initialWidth = 0
    private var initialHeight = 0



    private lateinit var listener: ButtonClickedListener

    interface ButtonClickedListener{
        fun onVideoCropStart()
        fun onVideoFavorite()
        fun onNoteClicked()
        fun onScreenShot()
        fun onNoteSave(markdownText:String)
        fun onVideoCropEnd():Boolean
    }

    private var isRecording = false

    fun addListener(listener:ButtonClickedListener){
        this.listener = listener
    }


    @SuppressLint("ClickableViewAccessibility")
    fun show() {
        if (!::binding.isInitialized) {
            binding = LayoutNotePanelHorizontalBinding.inflate(LayoutInflater.from(activity))

            // 初始位置
            binding.root.apply {
                x = 100f
                y = 300f
            }

            binding.editorView.setImagePickerLauncher(launcher)
            binding.editorView.addListener(this)

            binding.ivCut.setOnClickListener{
                if (!isRecording) {
                    listener.onVideoCropStart()
                    binding.ivCut.setImageResource(R.drawable.recording)
                    if (blinkAnimator == null) {
                        blinkAnimator =
                            ObjectAnimator.ofFloat(binding.ivClose, "alpha", 1f, 0f, 1f).apply {
                                duration = 1000 // 一秒一轮
                                repeatCount = ValueAnimator.INFINITE
                            }
                    }
                    blinkAnimator?.start()
                } else {
                    stopRecorder()
                }
                isRecording = !isRecording
            }

            binding.ivStar.setOnClickListener {
                listener.onVideoFavorite()
            }

            binding.ivScreenshot.setOnClickListener {
                listener.onScreenShot()
            }

            binding.icMarkdown.setOnClickListener {
                listener.onNoteClicked()
            }


            // 添加 resize handle 拖动逻辑
            binding.resizeHandle.setOnTouchListener { _, event ->
                when (event.actionMasked) {
                    MotionEvent.ACTION_DOWN -> {
                        resizeStartTime = System.currentTimeMillis()
                        initialTouchX = event.rawX
                        initialTouchY = event.rawY
                        initialWidth = binding.editorView.width
                        initialHeight = binding.editorView.height
                        isResizing = false
                    }

                    MotionEvent.ACTION_MOVE -> {
                        val elapsed = System.currentTimeMillis() - resizeStartTime
                        if (!isResizing && elapsed >= 1000) {
                            isResizing = true
                        }

                        if (isResizing) {
                            val dx = event.rawX - initialTouchX
                            val dy = event.rawY - initialTouchY

                            val newWidth = (initialWidth + dx).toInt().coerceAtLeast(200)
                            val newHeight = (initialHeight + dy).toInt().coerceAtLeast(200)

                            val layoutParams = binding.editorView.layoutParams
                            layoutParams.width = newWidth
                            layoutParams.height = newHeight
                            binding.editorView.layoutParams = layoutParams
                        }
                    }

                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        isResizing = false
                    }
                }
                true
            }

            binding.ivNote.setOnClickListener {
                if (binding.editorView.visibility == View.GONE) {
                    // 先确保 editorView 可测量
                    binding.editorView.visibility = View.INVISIBLE
                    binding.editorView.post {
                        // 测量展开后的整体大小
                        binding.root.measure(
                            View.MeasureSpec.UNSPECIFIED,
                            View.MeasureSpec.UNSPECIFIED
                        )
                        val totalW = binding.root.measuredWidth
                        val totalH = binding.root.measuredHeight

                        val rootX = binding.root.x
                        val rootY = binding.root.y
                        val parentW = rootView.width
                        val parentH = rootView.height

                        var newX = rootX
                        var newY = rootY

                        if (rootX + totalW > parentW) {
                            newX = parentW - totalW.toFloat()
                        }
                        if (rootY + totalH > parentH) {
                            newY = parentH - totalH.toFloat()
                        }

                        // 不允许负数（防止偏移出左上角）
                        newX = newX.coerceAtLeast(0f)
                        newY = newY.coerceAtLeast(0f)

                        // 平移动画
                        binding.root.animate()
                            .x(newX)
                            .y(newY)
                            .setDuration(200)
                            .withEndAction {
                                // 显示 editorView + 动画
                                binding.editorView.apply {
                                    alpha = 0f
                                    scaleX = 0.8f
                                    scaleY = 0.8f
                                    visibility = View.VISIBLE
                                    animate()
                                        .alpha(1f)
                                        .scaleX(1f)
                                        .scaleY(1f)
                                        .setDuration(200)
                                        .start()
                                }
                            }
                            .start()
                    }
                } else {
                    if (isNoteEmpty) {
                        animateCloseEditor()
                    } else {
                        AlertDialog.Builder(activity)
                            .setMessage("请先保存再关闭")
                            .setPositiveButton("保存") { _, _ ->
                                listener.onNoteSave(binding.editorView.exportMarkdown())
                                animateCloseEditor()
                            }
                            .setNegativeButton("不保存") { _, _ ->
                                binding.editorView.reset()
                                animateCloseEditor()
                            }
                            .show()
                    }
                }
            }

            binding.ivSave.setOnClickListener {
                listener?.onNoteSave(binding.editorView.exportMarkdown())
                binding.editorView.reset()
                binding.ivSave.visibility = View.GONE
                Toast.makeText(activity, "笔记已保存，点击Markdown标记查看",Toast.LENGTH_SHORT).show()
            }

            // 拖动逻辑，直接作用在整个 root 上也行，或者只作用在 ivDrag
            binding.ivDrag.setOnTouchListener { v, event ->
                when (event.actionMasked) {
                    MotionEvent.ACTION_DOWN -> {
                        dX = event.rawX - binding.root.x
                        dY = event.rawY - binding.root.y
                    }

                    MotionEvent.ACTION_MOVE -> {
                        // 计算新位置
                        val newX = (event.rawX - dX)
                        val newY = (event.rawY - dY)

                        // 限制不超出父布局
                        val parentW = rootView.width - binding.root.width
                        val parentH = rootView.height - binding.root.height
                        binding.root.x = newX.coerceIn(0f, parentW.toFloat())
                        binding.root.y = newY.coerceIn(0f, parentH.toFloat())
                    }
                }
                true
            }

            // 其他按钮的点击事件……
            binding.ivClose.setOnClickListener { hide() }
            // ……

            // 一定要带上 LayoutParams，保证后面重新 add 时也生效
            rootView.addView(
                binding.root, ConstraintLayout.LayoutParams(
                    ConstraintLayout.LayoutParams.WRAP_CONTENT,
                    ConstraintLayout.LayoutParams.WRAP_CONTENT
                )
            )
        } else {
            if (binding.root.parent == null) {
                // 重新 add，一定要带原 LayoutParams
                rootView.addView(binding.root, binding.root.layoutParams)
            }
        }

        isShowing = true
    }

    private fun stopRecorder() {
        val result = listener.onVideoCropEnd()
        if (result) {
            blinkAnimator?.cancel()
            binding.ivCut.setImageResource(R.drawable.baseline_content_cut_24)
        }
    }

    fun hide() {
        if (::binding.isInitialized) {
            rootView.removeView(binding.root)
            isShowing = false
        }
    }

    fun showNoteEditButtons() {
        binding.ivCut.visibility = View.GONE
        binding.ivStar.visibility = View.VISIBLE
        binding.ivScreenshot.visibility = View.VISIBLE
    }

    override fun onNoteChanged(isEmpty: Boolean) {
        binding.ivSave.visibility = if (isEmpty) View.GONE else View.VISIBLE
        isNoteEmpty = isEmpty
    }

    fun insertImage(uri: Uri) {
        binding.editorView.insertImage(uri)
    }


    private fun animateCloseEditor() {
        binding.editorView.animate()
            .alpha(0f)
            .scaleX(0.8f)
            .scaleY(0.8f)
            .setDuration(200)
            .withEndAction {
                binding.editorView.visibility = View.GONE
                binding.ivSave.visibility = View.GONE
            }
            .start()
    }

    fun stopRecord() {
        if (isRecording){
            isRecording = false
            binding.ivCut.setImageResource(R.drawable.baseline_content_cut_24)
        }
    }

}


